package com.cloud.logger.zchain.zchainserver.interceptor;

import com.cloud.logger.zchain.zchainserver.data.domain.Auditable;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;

/**
 * User: wcy
 * Date: 2017/9/6
 * Time: 10:16
 */
@Component
@Intercepts(value = { @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class CommonDataInterceptor implements Interceptor {

    private static final Log logger = LogFactory.getLog(CommonDataInterceptor.class);

    private Properties props = null;

//    @Autowired
//    AuditorAware<String> auditorAware;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object entity = invocation.getArgs()[1];
        if (entity instanceof Auditable) {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            @SuppressWarnings("unchecked")
            Auditable<String, ?> auditable = (Auditable<String, ?>) entity;
            Date operatedAt = new Date();
//            String currentAuditor = auditorAware.getCurrentAuditor();
            if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT) {
//                auditable.setCreatedBy(currentAuditor);
                auditable.setCreatedDate(operatedAt);
            }
//            auditable.setLastModifiedBy(currentAuditor);
            auditable.setLastModifiedDate(operatedAt);
        }
        return invocation.proceed();
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

}
